//顶点着色器程序
var VSHADER_SOURCE =
    'attribute vec4 a_Position;\n' +  //attribute被称为存储限定符，表示接下来的变量（a_Position）
    'attribute vec4 a_Color;\n' +
    'uniform mat4 u_ModelMatrix;\n' + //
    'varying vec4 v_Color;\n' +
    'void main() {\n' +
    'gl_Position = u_ModelMatrix * a_Position;\n' + //模型矩阵
    '  v_Color = a_Color;\n' +
    '}\n';

//片元着色器程序
var FSHADER_SOURCE =
    'precision mediump float;\n' +
    'varying vec4 v_Color;\n' +
    'void main() {\n' +
    // 'gl_FragColor = vec4(1.0,0.0,0.0,1.0);\n' + //设置颜色
    '  gl_FragColor = v_Color;\n' +
    '}\n';
var ANGLE = 0; //旋转角度
var colorParameter = 1; //颜色基数

function main() {
    //获取<canvas>元素
    var canvas = document.getElementById('webgl');
    //获取WebGL绘图上下文
    var gl = getWebGLContext(canvas);
    //初始化着色器
    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed to initialize shaders');
        return;
    }
    //获取attribute变量的存储位置--地址
    var a_Position = gl.getAttribLocation(gl.program, 'a_Position');//参数1：程序对象；参数2：想要获取存储地址的attribute变量名称；
    //设置顶点坐标位置
    var vertices = new Float32Array([
        0.0, 0.5,
        -0.5, -0.5,
        0.5, -0.5
    ]);
    var n = initVertexBuffers(gl, vertices);
    //创建Matrix4对象以进行模型变换
    var modelMatrix = new Matrix4();
    modelMatrix.rotate(ANGLE, 0, 0, 1); //设置模型矩阵为旋转矩阵
    //将模型矩阵传输给顶点着色器
    var u_ModelMatrix = gl.getUniformLocation(gl.program, 'u_ModelMatrix');
    gl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements);
    //设置颜色的位置
    var colors = [
        0.2, colorParameter, 0.8,
        0.8, colorParameter, 0.3,
        1.0, 0.5, colorParameter,
    ];
    //绘制颜色
    var m = colorBuffers(gl, colors);
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES, 0, n);//n is 3
    setTimeout(changeAngle, 2000)
}

function changeAngle() {
    colorParameter -= 0.2;
    ANGLE += 90;
    main();
}

function initVertexBuffers(gl, vertices) {
    var n = 3;//顶点的个数
    //创建缓冲区对象
    var vertexBuffer = gl.createBuffer();
    //将缓冲区对象绑定到目标
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    //向缓冲区对象中写入数据
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
    var a_Position = gl.getAttribLocation(gl.program, 'a_Position')
    //将缓冲区对象分配给a_Position变量
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
    //连接a_Position变量与分配给它的缓冲区对象
    gl.enableVertexAttribArray(a_Position);
    return n;
}

function colorBuffers(gl, colors) {
    var colorBuffer = gl.createBuffer();
    var n = 3;
    gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
    var a_Color = gl.getAttribLocation(gl.program, 'a_Color');
    gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(a_Color);
    return n;
}